/*
 * @Author: 段本显
 * @Desc: 文件简介
 * @Date: 2021-08-06 16:08:05
 * @LastEditors: 段本显
 * @LastEditTime: 2022-01-04 11:32:06
 * @Email: duanbenxian@jianq.com
 * @Mark: 如果有bug，那肯定不是我的锅，噜噜噜
 */
import { App } from 'vue'
import { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'

const history: any = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)
export default {
  install: (app: App) => {
    const router = app.config.globalProperties.$router
    const store = app.config.globalProperties.$store
    router.beforeEach(
      (
        to: RouteLocationNormalized,
        from: RouteLocationNormalized,
        next: NavigationGuardNext
      ) => {
        const toIndex = history.getItem(to.path)
        const fromIndex = history.getItem(from.path)
        if (toIndex) {
          if (
            !fromIndex ||
            parseInt(toIndex, 10) > parseInt(fromIndex, 10) ||
            (toIndex === '0' && fromIndex === '0')
          ) {
            store.commit('UPDATE_DIRECTION', { direction: 'forward' })
          } else {
            store.commit('UPDATE_DIRECTION', { direction: 'reverse' })
          }
        } else {
          ++historyCount
          history.setItem('count', historyCount)
          to.path !== '/' && history.setItem(to.path, historyCount)
          store.commit('UPDATE_DIRECTION', { direction: 'forward' })
        }
        next()
      }
    )
  },
}
